import requests
import os   # 用于创建保存目录
import time
from lxml import etree

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}
# 主 url
url = "https://w8.ixiuren.cc/"
# 获取热图榜单随机标签下的数据
params = {
    "f": "4"
}

# 将写入方法单独拿出来，方便后面做多线程写入
def func_writedata(woman_name,picture_name,picture_data):
    with open(f'./图片/{woman_name}/{picture_name}','wb') as f:
            f.write(picture_data)
    print(f'图片{picture_name}已保存')
# 获取前10页的数据
for i in range(1,11):
    if i == 1:
        response = requests.get(url + 'bang', headers=headers, params=params)
    else:
        response = requests.get(url + f'bang/page/{i}', headers=headers, params=params)
    e = etree.HTML(response.text)
    woman_url = e.xpath('//div[@class="hbox"]/div[2]/li/a/@href')    # 定位人物的url
    woman_name = e.xpath('//div[@class="hbox"]/div[2]/li/div[2]/div[2]/a/text()')   # 定位人物的名称
    if not os.path.exists('图片'):    # 在当前执行目录下创建图片目录
        os.mkdir('图片')
    for i,j in zip(woman_url,woman_name):
        j = j.replace(' ','_')
        if not os.path.exists(f'./图片/{j}'):    # 在当前执行目录下创建图片目录
            os.mkdir(f'./图片/{j}')
        resp = requests.get(url + i, headers=headers)
        pe = etree.HTML(resp.text)
        picture_url = pe.xpath('//div[@id="image"]/a/@href')
        for u in picture_url:
            picture_name = os.path.basename(u)
            print('https:' + u )
            picture_data = requests.get('https:' + u, headers=headers)
            func_writedata(j, picture_name, picture_data.content)
            break
        time.sleep(0.1)


